<template>
  <div class="report-builder">
    <el-form 
      ref="formRef" 
      :model="reportForm" 
      :rules="formRules" 
      label-width="120px"
      class="report-form"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报表名称" prop="name">
              <el-input 
                v-model="reportForm.name" 
                placeholder="请输入报表名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报表状态" prop="status">
              <el-select v-model="reportForm.status" placeholder="选择状态">
                <el-option label="草稿" value="draft" />
                <el-option label="已发布" value="published" />
                <el-option label="已归档" value="archived" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="报表描述" prop="description">
          <el-input 
            v-model="reportForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入报表描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </div>

      <!-- 数据源配置 -->
      <div class="form-section">
        <h3 class="section-title">数据源配置</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数据表" prop="dataSource">
              <el-select 
                v-model="reportForm.dataSource" 
                placeholder="选择数据表"
                @change="handleDataSourceChange"
              >
                <el-option 
                  v-for="table in dataTables" 
                  :key="table.value"
                  :label="table.label" 
                  :value="table.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时间字段" prop="timeField">
              <el-select 
                v-model="reportForm.timeField" 
                placeholder="选择时间字段"
                :disabled="!reportForm.dataSource"
              >
                <el-option 
                  v-for="field in timeFields" 
                  :key="field.value"
                  :label="field.label" 
                  :value="field.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 字段选择 -->
      <div class="form-section">
        <h3 class="section-title">字段选择</h3>
        <div class="field-selection">
          <div class="available-fields">
            <h4>可用字段</h4>
            <div class="field-list">
              <div 
                v-for="field in availableFields" 
                :key="field.value"
                class="field-item"
                draggable="true"
                @dragstart="handleDragStart($event, field)"
              >
                <el-icon><Grid /></el-icon>
                <span>{{ field.label }}</span>
                <span class="field-type">{{ field.type }}</span>
              </div>
            </div>
          </div>
          
          <div class="selected-fields">
            <h4>已选字段</h4>
            <div 
              class="field-drop-zone"
              @drop="handleDrop"
              @dragover.prevent
              @dragenter.prevent
            >
              <div 
                v-for="(field, index) in reportForm.selectedFields" 
                :key="field.value"
                class="selected-field-item"
              >
                <el-icon><Grid /></el-icon>
                <span>{{ field.label }}</span>
                <div class="field-actions">
                  <el-button 
                    size="small" 
                    type="primary" 
                    text
                    @click="configureField(field, index)"
                  >
                    配置
                  </el-button>
                  <el-button 
                    size="small" 
                    type="danger" 
                    text
                    @click="removeField(index)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
              <div v-if="reportForm.selectedFields.length === 0" class="empty-drop-zone">
                拖拽字段到此处
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 筛选条件 -->
      <div class="form-section">
        <h3 class="section-title">筛选条件</h3>
        <div class="filter-conditions">
          <div 
            v-for="(condition, index) in reportForm.filters" 
            :key="index"
            class="condition-item"
          >
            <el-row :gutter="10">
              <el-col :span="6">
                <el-select v-model="condition.field" placeholder="选择字段">
                  <el-option 
                    v-for="field in availableFields" 
                    :key="field.value"
                    :label="field.label" 
                    :value="field.value" 
                  />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-select v-model="condition.operator" placeholder="操作符">
                  <el-option label="等于" value="eq" />
                  <el-option label="不等于" value="ne" />
                  <el-option label="大于" value="gt" />
                  <el-option label="小于" value="lt" />
                  <el-option label="包含" value="like" />
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-input v-model="condition.value" placeholder="筛选值" />
              </el-col>
              <el-col :span="6">
                <el-button 
                  type="danger" 
                  @click="removeFilter(index)"
                  :disabled="reportForm.filters.length === 1"
                >
                  删除
                </el-button>
              </el-col>
            </el-row>
          </div>
          <el-button type="primary" @click="addFilter">添加筛选条件</el-button>
        </div>
      </div>

      <!-- 排序设置 -->
      <div class="form-section">
        <h3 class="section-title">排序设置</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序字段">
              <el-select v-model="reportForm.sortField" placeholder="选择排序字段">
                <el-option 
                  v-for="field in reportForm.selectedFields" 
                  :key="field.value"
                  :label="field.label" 
                  :value="field.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序方式">
              <el-radio-group v-model="reportForm.sortOrder">
                <el-radio label="asc">升序</el-radio>
                <el-radio label="desc">降序</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handlePreview">预览</el-button>
      <el-button type="success" @click="handleSave">保存</el-button>
    </div>

    <!-- 字段配置对话框 -->
    <el-dialog
      v-model="fieldConfigVisible"
      title="字段配置"
      width="500px"
    >
      <el-form 
        v-if="currentField"
        :model="currentField" 
        label-width="100px"
      >
        <el-form-item label="显示名称">
          <el-input v-model="currentField.displayName" />
        </el-form-item>
        <el-form-item label="数据格式">
          <el-select v-model="currentField.format">
            <el-option label="默认" value="default" />
            <el-option label="数字" value="number" />
            <el-option label="百分比" value="percent" />
            <el-option label="货币" value="currency" />
            <el-option label="日期" value="date" />
          </el-select>
        </el-form-item>
        <el-form-item label="聚合方式" v-if="currentField.type === 'number'">
          <el-select v-model="currentField.aggregation">
            <el-option label="求和" value="sum" />
            <el-option label="平均值" value="avg" />
            <el-option label="最大值" value="max" />
            <el-option label="最小值" value="min" />
            <el-option label="计数" value="count" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="fieldConfigVisible = false">取消</el-button>
        <el-button type="primary" @click="saveFieldConfig">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Grid } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  report: {
    type: Object,
    default: null
  },
  isEditing: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['save', 'cancel'])

// 响应式数据
const formRef = ref(null)
const fieldConfigVisible = ref(false)
const currentField = ref(null)
const currentFieldIndex = ref(-1)

// 表单数据
const reportForm = reactive({
  name: '',
  description: '',
  status: 'draft',
  dataSource: '',
  timeField: '',
  selectedFields: [],
  filters: [{ field: '', operator: 'eq', value: '' }],
  sortField: '',
  sortOrder: 'asc'
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入报表名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入报表描述', trigger: 'blur' }
  ],
  dataSource: [
    { required: true, message: '请选择数据表', trigger: 'change' }
  ]
}

// 数据表选项
const dataTables = ref([
  { label: '用户表', value: 'users' },
  { label: '订单表', value: 'orders' },
  { label: '商品表', value: 'products' },
  { label: '用户行为表', value: 'user_behaviors' }
])

// 时间字段选项
const timeFields = ref([])

// 可用字段
const availableFields = ref([])

// 计算属性
const selectedFieldValues = computed(() => {
  return reportForm.selectedFields.map(field => field.value)
})

// 方法
const handleDataSourceChange = () => {
  // 根据选择的数据表更新可用字段
  const fieldMap = {
    users: [
      { label: '用户ID', value: 'user_id', type: 'string' },
      { label: '用户名', value: 'username', type: 'string' },
      { label: '注册时间', value: 'created_at', type: 'date' },
      { label: '年龄', value: 'age', type: 'number' },
      { label: '性别', value: 'gender', type: 'string' }
    ],
    orders: [
      { label: '订单ID', value: 'order_id', type: 'string' },
      { label: '用户ID', value: 'user_id', type: 'string' },
      { label: '订单金额', value: 'amount', type: 'number' },
      { label: '订单时间', value: 'order_time', type: 'date' },
      { label: '订单状态', value: 'status', type: 'string' }
    ],
    products: [
      { label: '商品ID', value: 'product_id', type: 'string' },
      { label: '商品名称', value: 'product_name', type: 'string' },
      { label: '价格', value: 'price', type: 'number' },
      { label: '分类', value: 'category', type: 'string' },
      { label: '库存', value: 'stock', type: 'number' }
    ]
  }

  availableFields.value = fieldMap[reportForm.dataSource] || []
  
  // 更新时间字段选项
  timeFields.value = availableFields.value.filter(field => field.type === 'date')
  
  // 清空已选字段
  reportForm.selectedFields = []
}

const handleDragStart = (event, field) => {
  event.dataTransfer.setData('text/plain', JSON.stringify(field))
}

const handleDrop = (event) => {
  event.preventDefault()
  const fieldData = JSON.parse(event.dataTransfer.getData('text/plain'))
  
  // 检查是否已经添加过该字段
  if (!selectedFieldValues.value.includes(fieldData.value)) {
    reportForm.selectedFields.push({
      ...fieldData,
      displayName: fieldData.label,
      format: 'default',
      aggregation: fieldData.type === 'number' ? 'sum' : null
    })
  }
}

const removeField = (index) => {
  reportForm.selectedFields.splice(index, 1)
}

const configureField = (field, index) => {
  currentField.value = { ...field }
  currentFieldIndex.value = index
  fieldConfigVisible.value = true
}

const saveFieldConfig = () => {
  if (currentFieldIndex.value >= 0) {
    reportForm.selectedFields[currentFieldIndex.value] = { ...currentField.value }
  }
  fieldConfigVisible.value = false
}

const addFilter = () => {
  reportForm.filters.push({ field: '', operator: 'eq', value: '' })
}

const removeFilter = (index) => {
  reportForm.filters.splice(index, 1)
}

const handlePreview = () => {
  // 预览报表
  ElMessage.info('预览功能开发中...')
}

const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    if (reportForm.selectedFields.length === 0) {
      ElMessage.warning('请至少选择一个字段')
      return
    }

    emit('save', { ...reportForm })
  } catch (error) {
    ElMessage.error('请检查表单填写是否完整')
  }
}

const handleCancel = () => {
  emit('cancel')
}

// 初始化表单数据
const initForm = () => {
  if (props.isEditing && props.report) {
    Object.assign(reportForm, props.report)
  }
}

// 生命周期
onMounted(() => {
  initForm()
})
</script>

<style scoped>
.report-builder {
  max-height: 70vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e6e8eb;
  border-radius: 8px;
  background: #fafafa;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 16px;
  color: #303133;
  border-bottom: 1px solid #e6e8eb;
  padding-bottom: 10px;
}

.field-selection {
  display: flex;
  gap: 20px;
  min-height: 300px;
}

.available-fields,
.selected-fields {
  flex: 1;
}

.available-fields h4,
.selected-fields h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #606266;
}

.field-list {
  border: 1px solid #e6e8eb;
  border-radius: 4px;
  max-height: 250px;
  overflow-y: auto;
  background: white;
}

.field-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-bottom: 1px solid #f0f0f0;
  cursor: grab;
  transition: background-color 0.2s;
}

.field-item:hover {
  background-color: #f5f7fa;
}

.field-item:active {
  cursor: grabbing;
}

.field-type {
  margin-left: auto;
  font-size: 12px;
  color: #909399;
  background: #f0f0f0;
  padding: 2px 6px;
  border-radius: 3px;
}

.field-drop-zone {
  border: 2px dashed #e6e8eb;
  border-radius: 4px;
  min-height: 250px;
  padding: 12px;
  background: white;
  transition: border-color 0.2s;
}

.field-drop-zone:hover {
  border-color: #409EFF;
}

.selected-field-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  margin-bottom: 8px;
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
}

.field-actions {
  margin-left: auto;
  display: flex;
  gap: 4px;
}

.empty-drop-zone {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
}

.filter-conditions {
  background: white;
  padding: 16px;
  border-radius: 4px;
  border: 1px solid #e6e8eb;
}

.condition-item {
  margin-bottom: 12px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 0;
  border-top: 1px solid #e6e8eb;
  margin-top: 20px;
}
</style>
